<?php

namespace app\api\controller;

use app\common\controller\Api;
use app\common\library\Ems;
use app\common\library\Sms;
use fast\Random;
use think\Config;
use think\Model;
use think\Request;
use think\Validate;

/**
 * 会员接口
 */
class User extends Api
{
    protected $noNeedLogin = ['login', 'third', 'wxlogin', 'getWxCode', 'getWxInfo','image'];
    protected $noNeedRight = ['info','edit_isshow','index','del_image'];

    public function _initialize()
    {
        parent::_initialize();
    }

    /**
     * 会员中心
     */
    public function index()
    {
        $id=$this->auth->id;
        $info=Model('user')->where(['id'=>$id])->find();
        $complete['age']=$response['age'] = $info['age'];//年龄
        $response['loveId']=$info['love_id'];
        $response['height']=$info['height'];
        $response['weight']=$info['weight'];
        $response['status']=$info['examined']==2?'审核中':'已审核';

        $complete['birthday']=$info['birthday'];
        $complete['constellation']=$info['constellation'];
        $complete['education']=$info['education'];
        $complete['gender']=$info['gender'];
        $complete['zodiac']=$info['zodiac'];
        $complete['marry']=$info['marry'];
        $complete['income']=$info['income'];
        $complete['occupation']=$info['occupation'];
        $complete['character']=$info['character'];
        $complete['height']=$info['height'];
        $complete['weight']=$info['weight'];
        $complete['family']=$info['family'];
        $complete['address']=$info['address'];
        $complete['house']=$info['house'];
        $complete['is_car']=$info['is_car'];
        $complete['parents']=$info['parents'];
        $complete['hobby']=$info['hobby'];
        $complete['declaration']=$info['declaration'];


        $complete['is_divorce']=$info['is_divorce'];
        if ($complete==1){
            //如果上面有则有下面两个
            $complete['is_kids']=$info['is_kids'];
            $complete['kids_live']=$info['kids_live'];
        }


        $complete['content']=$info['content'];
        $complete['is_group']=$info['is_group'];
        $complete['betrothal_gifts']=$info['betrothal_gifts'];

        $complete['is_cook']=$info['is_cook'];
        //如果上面有则有下面这个
        if($complete['is_cook']==1){
            $complete['cook_list']=$info['cook_list'];
        }
        $complete['wx']=$info['wx'];

        $all=count($complete);
        $in=count(array_filter($complete));

        $completeP=ceil($in/$all);
        $response['complete']=$completeP;
        $response['levelName']='普通会员';
        $this->success('ok',['data'=>$response],200);
    }

    /**
     * 会员登录
     *
     * @param string $account 账号
     * @param string $password 密码
     */
    public function login()
    {
        $account = $this->request->request('account');
        $password = $this->request->request('password');
        if (!$account || !$password) {
            $this->error(__('Invalid parameters'));
        }
        $ret = $this->auth->login($account, $password);
        if ($ret) {
            $data = ['userinfo' => $this->auth->getUserinfo()];
            $this->success(__('Logged in successful'), $data);
        } else {
            $this->error($this->auth->getError());
        }
    }

    /**
     * 手机验证码登录
     *
     * @param string $mobile 手机号
     * @param string $captcha 验证码
     */
    public function mobilelogin()
    {
        $mobile = $this->request->request('mobile');
        $captcha = $this->request->request('captcha');
        if (!$mobile || !$captcha) {
            $this->error(__('Invalid parameters'));
        }
        if (!Validate::regex($mobile, "^1\d{10}$")) {
            $this->error(__('Mobile is incorrect'));
        }
        if (!Sms::check($mobile, $captcha, 'mobilelogin')) {
            $this->error(__('Captcha is incorrect'));
        }
        $user = \app\common\model\User::getByMobile($mobile);
        if ($user) {
            if ($user->status != 'normal') {
                $this->error(__('Account is locked'));
            }
            //如果已经有账号则直接登录
            $ret = $this->auth->direct($user->id);
        } else {
            $ret = $this->auth->register($mobile, Random::alnum(), '', $mobile, []);
        }
        if ($ret) {
            Sms::flush($mobile, 'mobilelogin');
            $data = ['userinfo' => $this->auth->getUserinfo()];
            $this->success(__('Logged in successful'), $data);
        } else {
            $this->error($this->auth->getError());
        }
    }

    /**
     * 注册会员
     *
     * @param string $username 用户名
     * @param string $password 密码
     * @param string $email 邮箱
     * @param string $mobile 手机号
     * @param string $code 验证码
     */
    public function register()
    {
        $username = $this->request->request('username');
        $password = $this->request->request('password');
        $email = $this->request->request('email');
        $mobile = $this->request->request('mobile');
        $code = $this->request->request('code');
        if (!$username || !$password) {
            $this->error(__('Invalid parameters'));
        }
        if ($email && !Validate::is($email, "email")) {
            $this->error(__('Email is incorrect'));
        }
        if ($mobile && !Validate::regex($mobile, "^1\d{10}$")) {
            $this->error(__('Mobile is incorrect'));
        }
        $ret = Sms::check($mobile, $code, 'register');
        if (!$ret) {
            $this->error(__('Captcha is incorrect'));
        }
        $ret = $this->auth->register($username, $password, $email, $mobile, []);
        if ($ret) {
            $data = ['userinfo' => $this->auth->getUserinfo()];
            $this->success(__('Sign up successful'), $data);
        } else {
            $this->error($this->auth->getError());
        }
    }

    /**
     * 退出登录
     */
    public function logout()
    {
        $this->auth->logout();
        $this->success(__('Logout successful'));
    }

    /**
     * 修改会员个人信息
     *
     * @param string $avatar 头像地址
     * @param string $username 用户名
     * @param string $nickname 昵称
     * @param string $bio 个人简介
     */
    public function profile()
    {
        $user = $this->auth->getUser();
        $username = $this->request->request('username');
        $nickname = $this->request->request('nickname');
        $bio = $this->request->request('bio');
        $avatar = $this->request->request('avatar', '', 'trim,strip_tags,htmlspecialchars');
        if ($username) {
            $exists = \app\common\model\User::where('username', $username)->where('id', '<>', $this->auth->id)->find();
            if ($exists) {
                $this->error(__('Username already exists'));
            }
            $user->username = $username;
        }
        if ($nickname) {
            $exists = \app\common\model\User::where('nickname', $nickname)->where('id', '<>', $this->auth->id)->find();
            if ($exists) {
                $this->error(__('Nickname already exists'));
            }
            $user->nickname = $nickname;
        }
        $user->bio = $bio;
        $user->avatar = $avatar;
        $user->save();
        $this->success();
    }

    /**
     * 修改邮箱
     *
     * @param string $email 邮箱
     * @param string $captcha 验证码
     */
    public function changeemail()
    {
        $user = $this->auth->getUser();
        $email = $this->request->post('email');
        $captcha = $this->request->request('captcha');
        if (!$email || !$captcha) {
            $this->error(__('Invalid parameters'));
        }
        if (!Validate::is($email, "email")) {
            $this->error(__('Email is incorrect'));
        }
        if (\app\common\model\User::where('email', $email)->where('id', '<>', $user->id)->find()) {
            $this->error(__('Email already exists'));
        }
        $result = Ems::check($email, $captcha, 'changeemail');
        if (!$result) {
            $this->error(__('Captcha is incorrect'));
        }
        $verification = $user->verification;
        $verification->email = 1;
        $user->verification = $verification;
        $user->email = $email;
        $user->save();

        Ems::flush($email, 'changeemail');
        $this->success();
    }

    /**
     * 修改手机号
     *
     * @param string $mobile 手机号
     * @param string $captcha 验证码
     */
    public function changemobile()
    {
        $user = $this->auth->getUser();
        $mobile = $this->request->request('mobile');
        $captcha = $this->request->request('captcha');
        if (!$mobile || !$captcha) {
            $this->error(__('Invalid parameters'));
        }
        if (!Validate::regex($mobile, "^1\d{10}$")) {
            $this->error(__('Mobile is incorrect'));
        }
        if (\app\common\model\User::where('mobile', $mobile)->where('id', '<>', $user->id)->find()) {
            $this->error(__('Mobile already exists'));
        }
        $result = Sms::check($mobile, $captcha, 'changemobile');
        if (!$result) {
            $this->error(__('Captcha is incorrect'));
        }
        $verification = $user->verification;
        $verification->mobile = 1;
        $user->verification = $verification;
        $user->mobile = $mobile;
        $user->save();

        Sms::flush($mobile, 'changemobile');
        $this->success();
    }

    /**
     * 第三方登录
     *
     * @param string $platform 平台名称
     * @param string $code Code码
     */
    public function third()
    {
        $url = url('user/index');
        $platform = $this->request->request("platform");
        $code = $this->request->request("code");
        $config = get_addon_config('third');
        if (!$config || !isset($config[$platform])) {
            $this->error(__('Invalid parameters'));
        }
        $app = new \addons\third\library\Application($config);
        //通过code换access_token和绑定会员
        $result = $app->{$platform}->getUserInfo(['code' => $code]);
        if ($result) {
            $loginret = \addons\third\library\Service::connect($platform, $result);
            if ($loginret) {
                $data = [
                    'userinfo' => $this->auth->getUserinfo(),
                    'thirdinfo' => $result
                ];
                $this->success(__('Logged in successful'), $data);
            }
        }
        $this->error(__('Operation failed'), $url);
    }

    /**
     * 重置密码
     *
     * @param string $mobile 手机号
     * @param string $newpassword 新密码
     * @param string $captcha 验证码
     */
    public function resetpwd()
    {
        $type = $this->request->request("type");
        $mobile = $this->request->request("mobile");
        $email = $this->request->request("email");
        $newpassword = $this->request->request("newpassword");
        $captcha = $this->request->request("captcha");
        if (!$newpassword || !$captcha) {
            $this->error(__('Invalid parameters'));
        }
        if ($type == 'mobile') {
            if (!Validate::regex($mobile, "^1\d{10}$")) {
                $this->error(__('Mobile is incorrect'));
            }
            $user = \app\common\model\User::getByMobile($mobile);
            if (!$user) {
                $this->error(__('User not found'));
            }
            $ret = Sms::check($mobile, $captcha, 'resetpwd');
            if (!$ret) {
                $this->error(__('Captcha is incorrect'));
            }
            Sms::flush($mobile, 'resetpwd');
        } else {
            if (!Validate::is($email, "email")) {
                $this->error(__('Email is incorrect'));
            }
            $user = \app\common\model\User::getByEmail($email);
            if (!$user) {
                $this->error(__('User not found'));
            }
            $ret = Ems::check($email, $captcha, 'resetpwd');
            if (!$ret) {
                $this->error(__('Captcha is incorrect'));
            }
            Ems::flush($email, 'resetpwd');
        }
        //模拟一次登录
        $this->auth->direct($user->id);
        $ret = $this->auth->changepwd($newpassword, '', true);
        if ($ret) {
            $this->success(__('Reset password successful'));
        } else {
            $this->error($this->auth->getError());
        }
    }


    /**
     * 获取wx信息
     * @ApiParam (name=code, type=string, required=true, description="jsCode")
     * @Apieturn mixed
     */
    public function getWxCode()
    {
        $code = input('code');
        if (!$code) {
            $this->error('js_code为空');
        }
        $info=$data = code2session($code);
        $row = Model('user')->field('id')->where(['open_id' => $data['openid']])->find();
        if ($row) {
            $this->auth->direct($row['id']);
            $data=$this->auth->getUserinfo();
            $data['register'] = 1;
            $data['session_key']=$info['session_key'];
            $data['openid']=$info['openid'];
        } else {
            $data['register'] = 0;
        }
        if (isset($data['errcode'])) {
            $this->error($data['errmsg']);
        } else {
            $return_data['data'] = $data;
            $this->success('请求成功', $data, 200);
        }
    }

    /**
     * 获取微信手机号
     * @ApiParams (name=session_key, type=string, required=true, description="session_key")
     * @ApiParams (name=openId, type=string, required=true, description="openId")
     * @ApiParams (name=data, type=json, required=true, description="数组json对象")
     */
    public function getWxInfo()
    {
        $session_key = input('session_key');
        $data = json_decode(urldecode(input('data')), true);
        //计算手机号等信息
        $appid = Config::get('wechat.app_id');
        $encryptedData = $data['encryptedData'];
        $iv = $data['iv'];
        $pc = new \app\api\library\WxBizDataCrypt($appid, $session_key);
        $errCode = $pc->decryptData($encryptedData, $iv, $data);
        if ($errCode != 0) {
            $error = [
                -41001 => 'encodingAesKey 非法',
                -41003 => 'aes解密失败',
                -41004 => '解密后得到的buffer非法',
                -41005 => 'base64加密失败 非法',
                -41016 => 'base64解密失败 非法',
            ];
            $this->error($error[$errCode]);
        }
        $info = json_decode($data, true);
        $this->success('ok', $info, 200);
    }

    /**
     * 微信登陆
     * @ApiParams (name=session_key, type=string, required=true, description="session_key")
     * @ApiParams (name=data, type=string, required=true, description="data")
     * @ApiParams (name=openId, type=string, required=true, description="openId")
     * @ApiParams (name=code, type=string, required=false, description="邀请（手机号）码")
     * @ApiParams (name=mobile, type=integer, required=true, description="手机号")
     * @ApiParams (name=captcha, type=integer, required=false, description="短信码（预留）")
     */
    public function wxlogin()
    {
        $session_key = input('session_key');
        $userInfo = json_decode(urldecode(input('userInfo')), true);
        $openId = input('openId');
        $code = $this->request->post('code');
        $mobile = $this->request->param('mobile');
        $data=json_decode( rawurldecode($this->request->param('data')),true) ;
        //$captcha=$this->request->param('captcha');
        $inviter='';
        if ($code) {
            //判断是否存在手机号
            $inviterInfo=Model('user')->field('id')->where(['status'=>'normal'])->find();
            $inviter= $inviterInfo['id'];
        }
        //计算手机号等信息
        $appid = Config::get('wechat.app_id');
        $encryptedData = $data['encryptedData'];
        $iv = $data['iv'];
        $pc = new \app\api\library\WxBizDataCrypt($appid, $session_key);
        $errCode = $pc->decryptData($encryptedData, $iv, $data);
        if ($errCode != 0) {
            $error = [
                -41001 => 'encodingAesKey 非法',
                -41003 => 'aes解密失败',
                -41004 => '解密后得到的buffer非法',
                -41005 => 'base64加密失败 非法',
                -41016 => 'base64解密失败 非法',
            ];
            $this->error($error[$errCode]);
        }

        if ($mobile && !Validate::regex($mobile, "^1\d{10}$")) {
            $this->error('手机号格式错误');
        }
        $user = \app\common\model\User::where(['open_id' => $openId])->find();
        if (is_null($user)) {
            //此处处理爱情号
            $num = Model('user')->order('love_id', 'desc')->column('love_id');
            $num = $num['0'] + 1;
            // $num = 11250;
            //获取最后2位数
            $numlast = substr($num, -2);
            //获取最后3位数
            $numlast1 = substr($num, -3);
            //10004 10025   10038   10114
            //id最后一位不能为4 不能为250   38   25
            $arr = array(04, 14, 34, 44, 54, 64, 74, 84, 94, 38);
            if (in_array($numlast, $arr)) {
                $num = $num + 1;
                //24单独拉出来   24下面25也不行
            } elseif ($numlast == 24) {
                $num = $num + 2;
            } elseif ($numlast1 == 250) {
                $num = $num + 1;
            } else {
                $num = $num;
            }
            $this->auth->register('',123456,'',$mobile,['open_id'=>$openId,'img'=>$userInfo['avatarUrl'],'gender'=>$userInfo['gender'],'inviter'=>$inviter,'avatar'=>$userInfo['avatarUrl'],'nickname'=>$userInfo['nickName'],'love_id'=>$num]);
        } else {
            $userId = $user['id'];
            $this->auth->direct($userId);
        }
        $userInfo = $this->auth->getUserinfo();
        $this->success(__('Logged in successful'), $userInfo, 200);
    }

    /**
     * 资料
     *
     * @ApiTitle    (资料修改)
     * @ApiMethod   (POST)
     * @ApiRoute    (/api/user/info)
     * @ApiHeaders  (name=token, type=string, required=true, description="请求的Token")
     * @ApiParams   (name="id", type="integer", required=true, description="会员ID")
     * @ApiParams   (name="username", type="string", required=true, description="姓名")
     * @ApiParams   (name="avatar", type="string", required=true, description="头像")
     * @ApiParams   (name="zodiac", type="string", required=true, description="生肖")
     * @ApiParams   (name="birthday", type="string", required=true, description="生日")
     * @ApiParams   (name="constellation", type="string", required=true, description="星座")
     * @ApiParams   (name="occupation", type="string", required=true, description="职业")
     * @ApiParams   (name="income", type="string", required=true, description="收入")
     * @ApiParams   (name="gender", type="string", required=true, description="性别")
     * @ApiParams   (name="character", type="string", required=true, description="性格")
     * @ApiParams   (name="height", type="string", required=true, description="身高")
     * @ApiParams   (name="address", type="string", required=true, description="地址")
     * @ApiParams   (name="wxis_show", type="string", required=true, description="微信号是否显示")
     * @ApiParams   (name="cook_list", type="array",sample="['番茄炒蛋','番茄炒蛋']", required=true, description="厨艺列表")
     * @ApiParams   (name="is_age", type="string", required=true, description="接受年龄")
     * @ApiParams   (name="is_divorce", type="string", required=true, description="离异")
     * @ApiParams   (name="is_kids", type="string", required=true, description="是否有小孩")
     * @ApiParams   (name="kids_live", type="string", required=false, description="小孩跟谁生活")
     * @ApiReturnParams   (name="code", type="integer", required=true, sample="0")
     * @ApiReturnParams   (name="msg", type="string", required=true, sample="返回成功")
     * @ApiReturn   ({
    'code':'200',
    'msg':'返回成功'
    })
     */
    public function info()
    {
        if ($this->request->isPost()) {
            $data = $this->request->post();
            $data['id']=$this->auth->id;
            if (empty($data['avatar'])) {
                $this->error('请输入头像', '',-1);
            }

            if (empty($data['username'])) {
                $this->error('请输入姓名', '',-1);
            }
            if (empty($data['zodiac'])) {
                $this->error('请输入生肖', '',-1);
            }
            if (empty($data['birthday'])) {
                $this->error('请输入生日', '',-1);
            }
            if (empty($data['constellation'])) {
                $this->error('请输入星座', '',-1);
            }
            if (empty($data['occupation'])) {
                $this->error('请输入职业', '',-1);
            }
            if (empty($data['income'])) {
                $this->error('请输入收入', '',-1);
            }
            if (empty($data['gender'])) {
                $this->error('请输入性别', '',-1);
            }
            if (empty($data['character'])) {
                $this->error('请输入性格', '',-1);
            }
            if (empty($data['height'])) {
                $this->error('请输入身高', '',-1);
            }
            //   if(empty($data['card'])){
            //   	 ajax_return(-1, "请输入证件照");
            //   }
            if (empty($data['address'])) {
                $this->error('请输入地址', '',-1);
            }
            if (empty($data['wxis_show'])) {
                $this->error('请输入微信号是否显示', '',-1);
            }
            if (empty($data['declaration'])){
                $this->error('请输入爱情宣言', '',-1);
            }
            if (empty($data['is_age'])){
                $this->error('请输入接受大小年龄范围', '',-1);
            }
            if (empty($data['is_divorce'])){
                $this->error('请输入是否接受离婚', '',-1);
            }
            if (empty($data['is_kids'])){
                $this->error('是否接受小孩', '',-1);
            }
            $data['create_time'] = time();

            $data['age'] = howOld(strtotime($data['birthday']));//年龄
            //判断是否有爱情号，如果有则不处理
            $love_id=Model('user')->where(['id'=>$data['id']])->field('love_id')->find();
            if(!$love_id) {
                //此处处理爱情号
                $num = Model('user')->order('id', 'desc')->column('love_id');
                $num = $num['0'] + 1;
                // $num = 11250;
                //获取最后2位数
                $numlast = substr($num, -2);
                //获取最后3位数
                $numlast1 = substr($num, -3);
                //10004 10025   10038   10114
                //id最后一位不能为4 不能为250   38   25
                $arr = array(04, 14, 34, 44, 54, 64, 74, 84, 94, 38);
                if (in_array($numlast, $arr)) {
                    $num = $num + 1;
                    //24单独拉出来   24下面25也不行
                } elseif ($numlast == 24) {
                    $num = $num + 2;
                } elseif ($numlast1 == 250) {
                    $num = $num + 1;
                } else {
                    $num = $num;
                }
                $data['love_id'] = $num;
                $love_id=$num;
            }else{
                $love_id=$love_id['love_id'];
            }
            if (Model('user')->update($data)) {
                $this->success('提交成功,等待审核,您的恋爱号为 : '.$love_id,'',200);
            } else {
                $this->success('提交失败','',-1);
            }
        }
    }

    /**
     * 是否展示微信
     *
     * @ApiTitle    (是否展示微信)
     * @ApiMethod   (POST)
     * @ApiRoute    (/api/user/edit_isshow)
     * @ApiHeaders  (name=token, type=string, required=true, description="请求的Token")
     * @ApiParams   (name="id", type="integer", required=true, description="会员ID")
     * @ApiParams   (name="wx_isshow", type="string", required=true, description="是否展示；2展示，1不展示")
     * @ApiReturnParams   (name="code", type="integer", required=true, sample="0")
     * @ApiReturnParams   (name="msg", type="string", required=true, sample="返回成功")
     * @ApiReturn   ({
    'code':'200',
    'msg':'返回成功'
    })
     */
    public function edit_isshow(){
        $wx_isshow = $_POST['wx_isshow'];
        $where['id'] = $this->auth->id;
        // 如果展示  让他隐藏
        if($wx_isshow == 1){
            $data['wxis_show'] = 2;
            if(Model('user')->where($where)->update($data) !== false){
                $this->success('隐藏成功',['code'=>2],200);
            }else{
                $this->error('请求错误,请稍后重试',['code'=>3],-1);
            }
        }elseif($wx_isshow == 2){
            $data['wxis_show'] = 1;
            if(Model('user')->where($where)->update($data) !== false){
                $this->success('展示成功',['code'=>1],200);
            }else{
                $this->error('请求错误,请稍后重试',['code'=>3],-1);
            }
        }else{
            $this->error('请求错误,请稍后重试',['code'=>3],-1);
        }
    }

    /**
     * 相册列表
     *
     * @ApiTitle    (相册列表)
     * @ApiMethod   (GET)
     * @ApiRoute    (/api/user/image)
     * @ApiHeaders  (name=token, type=string, required=true, description="请求的Token")
     * @ApiParams   (name="id", type="integer", required=true, description="会员ID")
     * @ApiReturnParams   (name="code", type="integer", required=true, sample="0")
     * @ApiReturnParams   (name="msg", type="string", required=true, sample="返回成功")
     * @ApiReturn   ({
    'code':'200',
    'msg':'返回成功'
    })
     */
    public function image(){
        $userid=$this->request->get('id');
        $list=Model('image')->where(['userid'=>$userid,'delete'=>0])->select();
        if ($list){
            $this->success('ok',['data'=>$list],200);
        }
        $this->error('未上传图片',['data'=>[]],-1);
    }

    /**
     * 相册删除
     *
     * @ApiTitle    (相册删除)
     * @ApiMethod   (POST)
     * @ApiRoute    (/api/user/del_image)
     * @ApiHeaders  (name=token, type=string, required=true, description="请求的Token")
     * @ApiParams   (name="id", type="integer", required=true, description="会员ID")
     * @ApiParams   (name="imageId", type="integer", required=true, description="图片ID")
     * @ApiReturnParams   (name="code", type="integer", required=true, sample="0")
     * @ApiReturnParams   (name="msg", type="string", required=true, sample="返回成功")
     * @ApiReturn   ({
    'code':'200',
    'msg':'返回成功'
    })
     */
    public function del_image()
    {
        $userid=$this->auth->id;
        $id=$this->request->post('imageId');
        $res=Model('image')->where(['id'=>$id,'userid'=>$userid])->update(['delete'=>1]);
        if($res){
            $this->success('删除成功','',200);
        }
        $this->error('删除失败，刷新后再试','',-1);
    }
}
